﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using VIBlend.WPF.Controls;
using System.Windows.Resources;

namespace AnonsaiWPF.CSharp.DataGridViewDemos
{
     [Category("VIBlend.WPF.Examples")]
    public partial class NestedGridsDemo : Window, IWindow
    {
         DataTemplate rowDetailsTemplate;
         DataTemplate ExpandCollapseCellDataTemplate;

         public void DetachContent()
         {
             RemoveLogicalChild(Content);
         }

         public void SetTheme()
         {
             dataGrid.FontFamily = new FontFamily("Tahoma");
         }
  
         public Grid Root
         {
             get
             {
                 return this.LayoutRoot;
             }
         }

        public NestedGridsDemo()
        {
            InitializeComponent();

            PrepareGridData();

            this.rowDetailsTemplate = this.Resources["rowDetailsTemplate"] as DataTemplate;
            this.ExpandCollapseCellDataTemplate = this.Resources["ExpandCollapseCellDataTemplate"] as DataTemplate;

            dataGrid.BoundFields.Add(new BoundField("CategoryID", "CategoryId"));
            dataGrid.BoundFields.Add(new BoundField("Category Name", "CategoryName"));
            dataGrid.BoundFields.Add(new BoundField("Description", "CategoryDescription"));

            foreach (HierarchyItem item in dataGrid.ColumnsHierarchy.Items)
            {
                item.CellStyle = Application.Current.Resources["TextCenteredCellStyle"] as Style;
            }

            dataGrid.BindingComplete += new EventHandler(dataGrid_BindingComplete);

            dataGrid.ItemsSource = categories;
            dataGrid.RowsHierarchy.Visible = false;

            dataGrid.ColumnsHierarchy.AllowResize = false;
            dataGrid.RowsHierarchy.AllowResize = false;

            dataGrid.CellMouseClick += new VIBlend.WPF.Controls.DataGrid.CellMouseButtonEventHandler(dataGrid_CellMouseClick);

            dataGrid.LoadRowDetails += new EventHandler<RowDetailsEventArgs>(dataGrid_LoadRowDetails);
            this.dataGrid.Refresh();
        }

        List<ProductInfo> products = new List<ProductInfo>();
        List<CategoryInfo> categories = new List<CategoryInfo>();

        private void PrepareGridData()
        {
            try
            {
                StreamResourceInfo sri = Application.GetResourceStream(new Uri("ExamplesCSharp;component/CSharp/DataGridViewDemos/products.tab", UriKind.Relative));
                System.IO.StreamReader sr = new System.IO.StreamReader(sri.Stream);
                string line = null;
                sr.ReadLine();
                while ((line = sr.ReadLine()) != null)
                {
                    string[] tabs = line.Split('\t');
                    ProductInfo product = new ProductInfo();
                    product.ProductId = int.Parse(tabs[0]);
                    product.ProductName = tabs[1];
                    product.CategoryId = int.Parse(tabs[3]);
                    product.UnitPrice = decimal.Parse(tabs[5]);
                    product.UnitsInStock = short.Parse(tabs[6]);
                    product.ReorderLevel = short.Parse(tabs[8]);

                    products.Add(product);
                }

                sr.Close();

                sri = Application.GetResourceStream(new Uri("ExamplesCSharp;component/CSharp/DataGridViewDemos/categories.tab", UriKind.Relative));
                sr = new System.IO.StreamReader(sri.Stream);
                sr.ReadLine();
                while ((line = sr.ReadLine()) != null)
                {
                    string[] tabs = line.Split('\t');
                    CategoryInfo category = new CategoryInfo();
                    category.CategoryId = int.Parse(tabs[0]);
                    category.CategoryName = tabs[1];
                    category.CategoryDescription = tabs[2];
                    
                    categories.Add(category);
                }
                sr.Close();
                
            }
            catch (System.Exception)
            {
            }
        }

        void dataGrid_LoadRowDetails(object sender, RowDetailsEventArgs e)
        {
            VIBlend.WPF.Controls.DataGrid nestedGrid = (VIBlend.WPF.Controls.DataGrid)e.RowDetailsElement.FindName("gridProducts");

            int categoryId = (int)dataGrid.CellsArea.GetCellValue(e.RowItem, dataGrid.ColumnsHierarchy.Items[1]);

            List<ProductInfo> results = new List<ProductInfo>();
            foreach (ProductInfo pinfo in products)
                if (pinfo.CategoryId == categoryId)
                    results.Add(pinfo);

            nestedGrid.ItemsSource = results;
            nestedGrid.ScrollBarsEnabled = true;
            nestedGrid.ColumnsHierarchy.AllowResize = true;

            nestedGrid.ColumnsHierarchy.Items[0].Width = 63;
            nestedGrid.ColumnsHierarchy.Items[1].Width = 71;
            nestedGrid.ColumnsHierarchy.Items[2].Width = 150;
            nestedGrid.ColumnsHierarchy.Items[3].Width = 79;
            nestedGrid.ColumnsHierarchy.Items[4].Width = 93;
            nestedGrid.ColumnsHierarchy.Items[5].Width = 93;
            nestedGrid.ColumnsHierarchy.AutoStretchColumns = true;

            foreach (HierarchyItem item in nestedGrid.ColumnsHierarchy.Items)
            {
                item.SortMode = GridItemSortMode.Automatic;
                item.CellStyle = Application.Current.Resources["TextCenteredCellStyle"] as Style;
            }
            nestedGrid.Refresh();

        }

        void dataGrid_CellMouseClick(object sender, CellMouseButtonEventArgs args)
        {
            if (args.Cell.ColumnItem == dataGrid.ColumnsHierarchy.Items[0])
            {
                args.Cell.RowItem.RowDetailsDataTemplate = rowDetailsTemplate;
                args.Cell.RowItem.RowDetailsVisiblity = (args.Cell.RowItem.RowDetailsVisiblity == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
                args.Cell.RowItem.RowDetailsHeight = 230;
                dataGrid.CellsArea.SetCellValue(args.Cell.RowItem, dataGrid.ColumnsHierarchy.Items[0], args.Cell.RowItem.RowDetailsVisiblity == Visibility.Visible);
            }
        }

        void dataGrid_BindingComplete(object sender, EventArgs e)
        {
            dataGrid.SelectionMode = VIBlend.WPF.Controls.DataGrid.SELECTION_MODE.FULL_ROW_SELECT;
            dataGrid.SelectionBorderEnabled = false;

            dataGrid.ColumnsHierarchy.Items.Insert(0, "");
            dataGrid.Refresh();

            dataGrid.ColumnsHierarchy.Items[0].CellDataTemplate = this.ExpandCollapseCellDataTemplate;

            dataGrid.ColumnsHierarchy.Items[0].Width = 25;
            dataGrid.ColumnsHierarchy.Items[1].Width = 100;
            dataGrid.ColumnsHierarchy.Items[2].Width = 150;
            dataGrid.ColumnsHierarchy.Items[3].Width = 384;
            foreach (HierarchyItem item in dataGrid.ColumnsHierarchy.Items)
            {
                item.CellStyle = Application.Current.Resources["TextCenteredCellStyle"] as Style;
            }

            foreach (HierarchyItem rowItem in dataGrid.RowsHierarchy.Items)
            {
                dataGrid.CellsArea.SetCellValue(rowItem, dataGrid.ColumnsHierarchy.Items[0], false);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            this.categories.Clear();
            this.categories = null;
            this.dataGrid.BindingComplete -= new EventHandler(dataGrid_BindingComplete);
            this.dataGrid.CellMouseClick -= new VIBlend.WPF.Controls.DataGrid.CellMouseButtonEventHandler(dataGrid_CellMouseClick);
            this.dataGrid.LoadRowDetails -= new EventHandler<RowDetailsEventArgs>(dataGrid_LoadRowDetails);

            this.dataGrid.Dispose();
            this.dataGrid = null;
        }
    }

    // Custom class implements the IValueConverter interface.
    public class BoolToImageUrlConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || ((bool)value) == false)
                return "images/plus.png";

            return "images/minus.png";
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }


    #region Sample Data

    public class CategoryInfo
    {
        public int CategoryId
        {
            get;
            set;
        }

        public string CategoryName
        {
            get;
            set;
        }

        public string CategoryDescription
        {
            get;
            set;
        }
    }

    public class ProductInfo
    {
        public int ProductId
        {
            get;
            set;
        }

        public int CategoryId
        {
            get;
            set;
        }

        public string ProductName
        {
            get;
            set;
        }

        public decimal UnitPrice
        {
            get;
            set;
        }

        public short UnitsInStock
        {
            get;
            set;
        }

        public short ReorderLevel
        {
            get;
            set;
        }
    }

    #endregion
}
